<template>
  <div class="app-container">
    <pro-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :total="total"
      :actionWidth="'160'"
      @query="handleQuery"
      @add="handleAdd"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @refresh="getList"
    >
      <template #toolbar-left>
        <el-button type="primary" :icon="Plus" @click="handleAdd"
          >新增租户</el-button
        >
      </template>

      <template #status="{ row }">
        <div class="status-container">
          <span
            class="status-label"
            :class="{
              'status-active': row.status === 0,
              'status-inactive': row.status === 1,
            }"
          >
            {{ getStatusLabel(row.status) }}
          </span>
        </div>
      </template>

      <template #businesslicense_img="{ row }">
        <div v-if="row.businesslicense_img" class="license-img-container">
          <el-image
            class="license-thumbnail"
            :src="formatImageUrl(row.businesslicense_img)"
            fit="cover"
            @click="showLicenseImage(row.businesslicense_img)"
          />
        </div>
        <span v-else>无图片</span>
      </template>

      <template #action="{ row }">
        <el-button type="success" link @click="handleUserInfo(row)">
          <el-icon><Search /></el-icon>账户
        </el-button>
        <el-button type="primary" link @click="handleEdit(row)">
          <el-icon><Edit /></el-icon>编辑
        </el-button>
      </template>
    </pro-table>

    <!-- 租户表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增租户' : '编辑租户'"
      width="800px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="租户公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入租户公司名称" />
        </el-form-item>
        <el-form-item
          label="租户帐号"
          prop="username"
          v-if="dialogType === 'add'"
        >
          <el-input v-model="form.username" placeholder="请输入租户帐号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input
            type="password"
            v-model="form.password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="password1"
          v-if="dialogType === 'add'"
        >
          <el-input
            type="password"
            v-model="form.password1"
            placeholder="请输入确认密码"
          />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="usci">
          <el-input v-model="form.usci" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="营业执照图片" prop="businesslicense_img">
          <image-upload
            :action="uploadUrl"
            :sysUploadType="'Tenant_businesslicense_img'"
            :image-url="form.businesslicense_img"
            @success="(url) => (form.businesslicense_img = url)"
            @error="() => (form.businesslicense_img = '')"
            tip-text="请上传营业执照图片，只支持jpg/png格式，大小不超过5MB"
          />
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalperson">
          <el-input v-model="form.legalperson" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="法人电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入法人电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 租户营业执照查看对话框 -->
    <el-dialog
      v-model="licenseImageVisible"
      title="营业执照查看"
      width="800px"
      :append-to-body="true"
      center
    >
      <div class="license-dialog-content">
        <el-image
          :src="currentLicenseImage"
          fit="contain"
          class="large-license-image"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="downloadLicenseImage">
            <el-icon><Download /></el-icon> 下载图片
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户账户信息对话框 -->
    <el-dialog
      v-model="userInfoDialog"
      title="租户账户信息"
      width="500px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="1" border v-loading="userInfoLoading">
        <el-descriptions-item label="账号">
          {{ userInfo.username || "暂无数据" }}
        </el-descriptions-item>
        <el-descriptions-item label="账户类型">
          {{ userInfo.userTypeName || "暂无数据" }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userInfoDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Download } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {
  getTenantList,
  addTenant,
  updateTenant,
  checkusci,
  getTenantUserInfo,
} from "@/api/modules/tenant";
import { checkusername } from "@/api/modules/user";
import { getSelectControlEnumList } from "@/api/modules/selectcontrol";

// 列配置
const columns = [
  {
    prop: "name",
    label: "租户名称",
    minWidth: "150",
    search: true,
  },
  {
    prop: "businesslicense_img",
    label: "营业执照",
    minWidth: "100",
    align: "center",
    slot: "businesslicense_img",
  },
  {
    prop: "usci",
    label: "统一社会信用代码",
    minWidth: "220",
    search: true,
  },
  {
    prop: "legalperson",
    label: "法人姓名",
    minWidth: "80",
    align: "center",
  },
  {
    prop: "telephone",
    label: "联系电话",
    minWidth: "130",
  },
  {
    prop: "status",
    label: "租户状态",
    minWidth: "140",
    search: true,
    searchType: "select",
    options: [], // 使用普通数组而不是ref
    slot: "status",
  },
  {
    prop: "createtime",
    label: "创建时间",
    minWidth: "170",
  },
];

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const selectedRows = ref([]);

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const formRef = ref(null);

// 用户账户信息对话框
const userInfoDialog = ref(false);
const userInfo = ref({});
const userInfoLoading = ref(false);

// 营业执照查看相关
const licenseImageVisible = ref(false);
const currentLicenseImage = ref('');

// 上传URL
const uploadUrl = import.meta.env.VITE_API_URL + "/api/v1/Images/upload";

// 防抖函数
const debounce = (fn, delay = 300) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 验证用户名是否重复
const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入租户帐号"));
    return;
  }

  // 编辑时如果用户名未修改，则不验证
  if (dialogType.value === "edit" && value === form.value.originalUsername) {
    callback();
    return;
  }

  checkusername({ username: value })
    .then((response) => {
      if (response.data) {
        callback(new Error("该租户帐号已存在"));
      } else {
        callback();
      }
    })
    .catch(() => {
      callback(new Error("用户名验证失败，请重试"));
    });
};

// 验证统一社会信用代码是否重复
const validateUsci = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入统一社会信用代码"));
    return;
  }

  // 编辑时如果社会信用代码未修改，则不验证
  if (dialogType.value === "edit" && value === form.value.originalUsci) {
    callback();
    return;
  }

  checkusci({ usci: value })
    .then((response) => {
      if (response.data) {
        callback(new Error("该统一社会信用代码已存在"));
      } else {
        callback();
      }
    })
    .catch(() => {
      callback(new Error("统一社会信用代码验证失败，请重试"));
    });
};

// 创建防抖验证函数
const debouncedValidateUsername = debounce(validateUsername, 500);
const debouncedValidateUsci = debounce(validateUsci, 500);

const form = ref({
  name: "",
  username: "",
  password: "",
  password1: "",
  usci: "",
  legalperson: "",
  telephone: "",
  businesslicense_img: "",
  originalUsername: "", // 添加原始用户名，用于编辑时判断是否修改
  originalUsci: "", // 添加原始统一社会信用代码，用于编辑时判断是否修改
});

const rules = {
  name: [
    { required: true, message: "请输入租户名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入租户帐号", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{2,20}$/,
      message: "租户帐号只能包含大小写字母和数字",
      trigger: "blur",
    },
    { validator: debouncedValidateUsername, trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6个字符", trigger: "blur" },
  ],
  password1: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  usci: [
    { required: true, message: "请输入统一社会信用代码", trigger: "blur" },
    { validator: debouncedValidateUsci, trigger: "blur" },
  ],
  businesslicense_img: [
    { required: true, message: "必须上传营业执照图片", trigger: "blur" },
  ],
  legalperson: [{ required: true, message: "请输入法人姓名", trigger: "blur" }],
  telephone: [
    { required: true, message: "请输入法人电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

// 获取列表数据
const getList = async (params) => {
  loading.value = true;
  try {
    if (!params) {
      params = {
        pageNum: 1,
        pageSize: 10,
      };
    }
    const res = await getTenantList(params);
    tableData.value = res.data.items;
    total.value = res.data.total;
  } catch (error) {
    console.error("获取租户列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = (params) => {
  getList(params);
};

// 新增租户
const handleAdd = () => {
  dialogType.value = "add";
  form.value = {
    name: "",
    username: "",
    password: "",
    password1: "",
    usci: "",
    legalperson: "",
    telephone: "",
    businesslicense_img: "",
    originalUsername: "", // 添加原始用户名，用于编辑时判断是否修改
    originalUsci: "", // 添加原始统一社会信用代码，用于编辑时判断是否修改
  };
  dialogVisible.value = true;
};

// 编辑租户
const handleEdit = (row) => {
  dialogType.value = "edit";
  form.value = { ...row };
  form.value.originalUsername = row.username;
  form.value.originalUsci = row.usci;
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          const params = {
            name: form.value.name,
            usci: form.value.usci,
            businesslicense_img: form.value.businesslicense_img.url,
            legalperson: form.value.legalperson,
            telephone: form.value.telephone,
            loginReq: {
              username: form.value.username,
              password: form.value.password,
            },
          };
          await addTenant(params).then((res) => {
            if (res.data) {
              ElMessage.success("添加成功");
            } else {
              ElMessage.error("添加失败" + res.message);
            }
          });
        } else {
          const params = {
            id: form.value.id,
            name: form.value.name,
            usci: form.value.usci,
            businesslicense_img: typeof form.value.businesslicense_img === 'object' ? form.value.businesslicense_img.url : form.value.businesslicense_img,
            legalperson: form.value.legalperson,
            telephone: form.value.telephone
          };
          await updateTenant(params).then((res) => {
            if (res.data) {
              ElMessage.success("更新成功");
            } else {
              ElMessage.error("更新失败" + res.message);
            }
          });
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("提交失败:", error);
      }
    }
  });
};

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 分页
const handleSizeChange = (val) => {
  getList({ pageSize: val });
};

const handleCurrentChange = (val) => {
  getList({ pageNum: val });
};

// 获取租户状态枚举列表
const getTenantStatusOptions = async () => {
  try {
    const res = await getSelectControlEnumList({ enumname: "UsersStatus" });
    if (res.data && Array.isArray(res.data)) {
      // 过滤掉任何可能有undefined或null值的项
      const validOptions = res.data
        .filter(
          (item) =>
            item &&
            item.description &&
            item.id !== undefined &&
            item.id !== null
        )
        .map((item) => ({
          label: item.description,
          value: item.id,
        }));

      // 更新状态选项
      const statusColumn = columns.find((col) => col.prop === "status");
      if (statusColumn) {
        statusColumn.options = validOptions;
      }
    }
  } catch (error) {
    console.error("获取租户状态枚举失败:", error);
  }
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statusOptions = columns.find((col) => col.prop === "status").options;
  const statusItem = statusOptions.find((opt) => opt.value === status);
  return statusItem ? statusItem.label : status;
};

// 查看租户用户账户信息
const handleUserInfo = async (row) => {
  userInfoLoading.value = true;
  userInfoDialog.value = true;
  userInfo.value = {}; // 重置信息

  try {
    const res = await getTenantUserInfo({ id: row.id });
    if (res && res.data) {
      userInfo.value = res.data;
    } else {
      ElMessage.warning("未找到该租户的账户信息");
    }
  } catch (error) {
    ElMessage.error("获取租户账户信息失败");
  } finally {
    userInfoLoading.value = false;
  }
};

// 显示营业执照大图
const showLicenseImage = (imageUrl) => {
  currentLicenseImage.value = formatImageUrl(imageUrl);
  licenseImageVisible.value = true;
};

// 下载营业执照图片
const downloadLicenseImage = () => {
  if (!currentLicenseImage.value) {
    ElMessage.warning('无图片可下载');
    return;
  }
  
  // 创建一个临时的a标签用于下载
  const link = document.createElement('a');
  link.href = currentLicenseImage.value;
  
  // 从URL中提取文件名，如果无法提取则使用默认名称
  const urlParts = currentLicenseImage.value.split('/');
  const fileName = urlParts[urlParts.length - 1].split('?')[0] || '营业执照.png';
  
  // 设置下载的文件名
  link.download = fileName;
  
  // 触发点击事件开始下载
  document.body.appendChild(link);
  link.click();
  
  // 清理DOM
  document.body.removeChild(link);
  
  ElMessage.success('图片下载中...');
};

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return '';
  
  // 如果是对象类型并包含url属性
  if (typeof url === 'object' && url.url) {
    url = url.url;
  }
  
  // 检查是否已经包含http，如果不包含则添加baseUrl
  if (url.startsWith('http')) {
    return url;
  } else {
    return import.meta.env.VITE_API_URL + url;
  }
};

// 组件加载时初始化数据
const initData = async () => {
  // 先完成获取租户状态选项
  await getTenantStatusOptions();
  // 状态选项加载完成后再获取列表
  await getList();
};

onMounted(() => {
  initData();
});

// 格式化日期，显示年月日
function formatDate(date) {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

:deep(.el-date-editor) {
  width: 100%;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-icon) {
  margin-right: 4px;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-label {
  font-size: 13px;
  padding: 2px 6px;
  border-radius: 4px;
}

.status-active {
  color: #67c23a;
  background-color: #f0f9eb;
}

.status-inactive {
  color: #909399;
  background-color: #f4f4f5;
}

.license-img-container {
  display: flex;
  justify-content: center;
}

.license-thumbnail {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  object-fit: cover;
}

.license-thumbnail:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.license-dialog-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.large-license-image {
  max-width: 100%;
  max-height: 100%;
}
</style>
